const fs = require('fs');
const COS = require('cos-nodejs-sdk-v5');

class UploadToTencentCOS{
  constructor(options){
    let {SecretId = "", SecretKey = ""} = options;
    this.Bucket = options.Bucket;
    this.Region = options.Region;
    this.cos = new COS({
      SecretId,
      SecretKey
    })
  }
  apply(compiler){
    compiler.hooks.afterEmit.tapPromise('UploadToTencentCOS', (compilation) => {
      const assets = compilation.assets;
      const promises = [];
      Object.keys(assets).forEach(filename => {
        promises.push(this.uploadFile(filename))
      })
      return Promise.all(promises)
    })
  }
  uploadFile(filename){
    return new Promise((resolve, reject) => {
      this.cos.putObject({
        Bucket: this.Bucket,
        Region: this.Region,
        Key: filename,
        Body: fs.createReadStream('./dist' + '/' + filename)
      }, function(err, data){
        if(err) reject(err);
        resolve(data);
      })
    })
  }
}

module.exports = UploadToTencentCOS